<template>
  <div class="page-container">
    <!-- 主内容区 -->
    <div class="dashboard">
      <div class="content-area">
        <!-- 操作工具栏 -->
        <div class="operation-toolbar">
          <!-- 左侧标题区域 -->
          <div class="toolbar-title">用户管理</div>

          <!-- 右侧操作按钮组 -->
          <div class="button-group">
            <el-button size="small" type="primary" @click="handleAdd">
              <i class="el-icon-plus"></i> 添加
            </el-button>
            <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
              <el-form
                  :model="form"
                  :rules="rules"
                  ref="ruleForm"
                  :label-width="formLabelWidth"
                  class="demo-ruleForm"
              >
                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 密码（6-8位验证） -->
                <el-form-item label="密码" prop="password">
                  <el-input v-model="form.password" type="password" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 手机号（格式验证） -->
                <el-form-item label="联系方式" prop="phone">
                  <el-input v-model="form.phone" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 性别 -->
                <el-form-item label="性别" prop="sex">
                  <el-select v-model="form.sex" placeholder="请选择">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="0"></el-option>
                  </el-select>
                </el-form-item>

                <!-- 提交按钮 -->
                <el-form-item>
                  <div style="float: right">
                    <el-button type="primary" @click="handleSubmit">提交</el-button>
                    <el-button @click="resetForm">重置</el-button>
                  </div>

                </el-form-item>
              </el-form>
            </el-dialog>
            <el-button size="small" type="primary" @click="fetchData" style="margin-left: 10px;">
              <i class="el-icon-refresh"></i> 刷新
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="batchDelete"
                :loading="deleteLoading"
                v-if="multipleSelection.length > 0"
                style="margin-left: 10px;">
              <i class="el-icon-delete"></i> 批量删除
            </el-button>
          </div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-container">
          <el-row :gutter="15" class="search-row">
            <el-col :span="6">
              <el-input
                  v-model="searchForm.username"
                  placeholder="请输入用户名搜索"
                  clearable
                  @keyup.enter.native="handleSearch"
                  size="small">
              </el-input>
            </el-col>
            <el-col :span="5">
              <el-select
                  v-model="searchForm.sex"
                  placeholder="请选择性别"
                  clearable
                  @change="handleSearch"
                  size="small">
                <el-option label="全部" value=""></el-option>
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="0"></el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" size="small" @click="handleSearch" style="width: 100%;">搜索</el-button>
            </el-col>
            <el-col :span="3">
              <el-button type="default" size="small" @click="resetSearch" style="width: 100%;">重置</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          ref="table"
          border
          size="small">
        <!-- 全选复选框列 -->
        <el-table-column
            type="selection"
            width="50">
        </el-table-column>

        <el-table-column
            prop="id"
            label="id"
            width="60px">
        </el-table-column>

        <el-table-column
            prop="username"
            label="用户名"
            width="90px">
        </el-table-column>

        <el-table-column
            prop="sex"
            label="性别"
            width="70px">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sex === 1">男</el-tag>
            <el-tag v-else>女</el-tag>
          </template>
        </el-table-column>

        <el-table-column
            prop="phone"
            label="联系方式">
        </el-table-column>

        <el-table-column
            prop="createTime"
            label="创建时间">
        </el-table-column>

        <el-table-column
            prop="money"
            label="余额">
          <template slot-scope="scope">
            <el-tag>{{scope.row.money.toFixed(2)}}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
            label="操作"
            width="140px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-dialog title="编辑信息" :visible.sync="dialogFormVisibleE">
              <el-form
                  :model="form"
                  :rules="rules"
                  ref="ruleForm"
                  :label-width="formLabelWidth"
                  class="demo-ruleForm"
              >
                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 密码（6-8位验证） -->
                <el-form-item label="密码" prop="password">
                  <el-input v-model="form.password" type="password" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 手机号（格式验证） -->
                <el-form-item label="联系方式" prop="phone">
                  <el-input v-model="form.phone" autocomplete="off"></el-input>
                </el-form-item>

                <!-- 性别 -->
                <el-form-item label="性别" prop="sex">
                  <el-select v-model="form.sex" placeholder="请选择">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="0"></el-option>
                  </el-select>
                </el-form-item>

                <!-- 提交按钮 -->
                <el-form-item>
                  <div style="float: right">
                    <el-button type="primary" @click="handleEditSubmit">提交</el-button>
                    <el-button @click="dialogFormVisibleE = false">取消</el-button>
                  </div>

                </el-form-item>
              </el-form>
            </el-dialog>
            <el-button type="danger" size="mini" @click="deleteSingle(scope.row)" style="margin-left: 5px;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {getUserInfo} from "@/api/user"; // 查询用户的API
import { deleteUsers } from "@/api/user"; // 删除用户的API
import { addUser } from "@/api/user"; // 添加用户的API
import { updateUser } from "@/api/user" //更新用户的API

export default {
  name: "UserControllerView",
  data() {
    // 自定义手机号验证器
    const validatePhone = (rule, value, callback) => {
      // 手机号正则：1开头，第二位3-9，后面9位数字
      const phoneReg = /^1[3-9]\d{9}$/;

      if (!value) {
        // 未输入时的警告
        return callback(new Error('请输入手机号'));
      }

      if (!phoneReg.test(value)) {
        // 格式错误时的警告
        return callback(new Error('手机号格式不正确（11位有效数字）'));
      }

      // 验证通过
      callback();
    };
    return {
      checked: false,
      checkAll: false,
      isIndeterminate: false,
      tableData: [],
      multipleSelection: [], // 存储选中的行数据
      searchForm: { // 搜索表单数据
        username: '',
        sex: '',
        pageNum: 1, // 当前页码
        pageSize: 5, // 每页显示的记录数
      },
      deleteLoading: false, // 删除操作加载状态
      // 分页参数
      pageInfo: {
        pageNum: 1, // 当前页码
        pageSize: 5, // 每页显示的记录数
        total: null, // 总记录数
        pages: null // 总页数
      },
      dialogFormVisible: false,// 对话框显示状态
      dialogFormVisibleE: false,
      form: {
        id: null,
        username: null,
        password: null,
        phone: '',
        sex: '',
      },
      formLabelWidth: '120px',
      // 验证规则配置
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 8, message: '密码长度必须为6-8位', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.fetchData(this.searchForm);
  },
  // computed: {
  //   // 根据搜索条件过滤表格数据
  //   filteredTableData() {
  //     return this.tableData.filter(row => {
  //
  //       // 用户名搜索（不区分大小写）
  //       const usernameMatch = this.searchForm.username
  //           ? row.username.toLowerCase().includes(this.searchForm.username.toLowerCase())
  //           : true;
  //       // 性别筛选
  //       const sexMatch = this.searchForm.sex !== ''
  //           ? row.sex.toString() === this.searchForm.sex
  //           : true;
  //       return usernameMatch && sexMatch;
  //     });
  //   }
  // },
  methods: {
    // 分页相关方法
    handleSizeChange(val) {
      if (this.searchForm.pageSize === val) return; // 值未变化时不执行
      console.log(`每页 ${val} 条`);
      this.searchForm.pageSize = val;
      this.searchForm.currentPage = 1; // 通常切换页大小时会重置到第一页
      this.fetchData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.pageNum = val;
      this.fetchData();
    },

    /**
     * 加载表格数据
     */
    fetchData() {
      // 添加加载动画
      this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      getUserInfo(this.searchForm).then(res => {
        this.tableData = res.data.list || [];
        this.pageInfo.total = res.data.total;
        this.pageInfo.pages = res.data.pages;
        this.pageInfo.pageNum = res.data.pageNum;
        this.pageInfo.pageSize = res.data.pageSize;
        this.$loading().close();
      }).catch(error => {
        console.error('数据加载失败:', error);
        this.$loading().close();
        this.$message.error('数据加载失败，请重试');
      });
    },

    /**
     * 处理选择变化
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // 更新全选状态
      this.checkAll = this.tableData.length > 0 && val.length === this.tableData.length;
      // 更新半选状态
      this.isIndeterminate = val.length > 0 && val.length < this.tableData.length;
    },

    /**
     * 全选/取消全选
     */
    handleCheckAllChange(val) {
      this.$refs.table.toggleAllSelection();
    },

    /**
     * 搜索处理
     * TODO: 实现后端搜索接口调用
     */
    handleSearch() {
      console.log('搜索条件:', this.searchForm);
      this.fetchData(this.searchForm);
    },

    /**
     * 重置搜索条件
     */
    resetSearch() {
      this.searchForm = {
        username: '',
        sex: '',
        pageNum: 1,
        pageSize: 5
      };
      this.fetchData();
    },



    /**
     * 批量删除
     */
    batchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的用户');
        return;
      }
      // 删除数据的数量
      this.$confirm(`确定要删除选中的 ${this.multipleSelection.length} 条数据吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteLoading = true;
        // 获取选中用户的ID数组
        const ids = this.multipleSelection.map(item => item.id);

        // 调用删除API
        deleteUsers(ids).then(res => {
          this.deleteLoading = false;
          this.$message.success('删除成功');
          this.fetchData(); // 重新加载数据
          this.$refs.table.clearSelection(); // 清空选择
        }).catch(error => {
          this.deleteLoading = false;
          console.error('删除失败:', error);
          this.$message.error('删除失败，请重试');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    /**
     * 单个删除
     */
    deleteSingle(row) {
      // 关键：$confirm 的返回值必须链式调用 then/catch，不能加 await（除非用 try/catch）
      this.$confirm(
          `确定要删除用户 "${row.username}" 吗?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        // 点击“确定”后进入这里：执行删除 API 调用
        deleteUsers([row.id]).then(res => {
          this.$message.success('删除成功');
          this.searchForm.pageNum = 1;
          this.fetchData();
        }).catch(apiError => {
          // 这里是 API 请求失败的逻辑（如网络错误、后端报错），不是“取消删除”
          console.error('删除请求失败:', apiError);
          this.$message.error('删除失败，请重试');
        });
      }).catch(confirmError => {
        // 这里才是“取消删除”的逻辑（点击取消/关闭弹窗）
        this.$message.info('已取消删除');
        // 可选：打印错误，排查是否误触发（若确定时进入这里，会有错误信息）
        console.log('弹窗操作被取消:', confirmError);
      });
    },

    /**
     * 编辑用户
     * TODO: 实现编辑功能，打开编辑弹窗或跳转到编辑页面
     */
    handleEdit(row) {
      console.log('编辑用户:', row);
      this.dialogFormVisibleE = true;
      this.form = {
        id: row.id,
        username: row.username,
        password: row.password,
        phone: row.phone,
        sex: row.sex.toString(),
      };
    },
    /**
     * 编辑用户提交表单
     */
    handleEditSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 验证通过，可提交数据
          alert('表单验证通过，即将提交！');
          console.log('表单数据:', this.form);
          this.dialogFormVisibleE = false;
          console.log("表单数据=>", this.form);
          // 调用修改API
          updateUser(this.form).then(res => {
            if (res.code === 200) {
              this.$message.success("修改成功");
            }else {
              this.$message.error("修改失败");
            }
            this.fetchData();
          })
        }else {
          // 验证失败，输入框会自动显示红色警告
          console.log('表单验证失败');
          this.$message.error('请填写正确的表单数据');
          return false;
        }
      });
    },

    /**
     * 添加用户
     * TODO: 实现添加功能，打开添加弹窗或跳转到添加页面
     */
    handleAdd() {
      this.dialogFormVisible = true;
    },
    /**
     * 添加用户提交表单
     */
    handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 验证通过，可提交数据
          alert('表单验证通过，即将提交！');
          console.log('表单数据:', this.form);
          this.dialogFormVisible = false;
          console.log("表单数据=>", this.form)
          addUser(this.form).then(res => {
            if (res.code === 200) {
              this.$message.success("添加成功");
              this.fetchData();
            } else {
              this.$message.error("添加失败");
            }
          });
        } else {
          // 验证失败，输入框会自动显示红色警告
          console.log('表单验证失败');
          return false;
        }
      });
    },
    // 重置表单
    resetForm() {
      this.$refs.ruleForm.resetFields();
    }
  }
};
</script>

<style scoped>
.page-container {
  padding: 5px;
}
.dashboard {
  width: 103%;
  max-width: 1200px;
  margin: 0 auto 20px;
}

.content-area {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 操作工具栏样式 */
.operation-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.toolbar-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.button-group {
  display: flex;
  align-items: center;
}

/* 搜索区域样式 */
.search-container {
  margin-bottom: 10px;
}

.search-row {
  display: flex;
  align-items: center;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}
</style>
